# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import MySQLdb

from scrapy.exceptions import DropItem

class MyscrapyPipeline(object):
    def process_item(self, item, spider):
        return item

class CommentPipline(object):
	def __init__(self):
		self.db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="root", port=3306, db="myscrapy", charset="utf8")
		self.cursor = self.db.cursor()

	def process_item(self, item, spider):
		sql = "SELECT * FROM `myscrapy`.`comments` WHERE `id`='"+item["_id"]+"';"
		lines = self.cursor.execute(sql)
		ret = self.cursor.fetchone()
		if ("" == ret) or (None == ret):
			sql = "INSERT INTO `myscrapy`.`comments` (`id`, `author_code`, `author`, `time`, `comment`, `support`, `unsupport`) VALUES ('"+item["_id"]+"', '"+item["author_code"]+"', '"+item["author"]+"', "+repr(item["time"])+", '"+item["comment"]+"', '"+item["support"]+"', '"+item["unsupport"]+"');"
			# print sql
			lines = self.cursor.execute(sql)
			self.db.commit()
			return item
			# raise DropItem("Scrapped a comment")
		else:
			sql = "UPDATE `myscrapy`.`comments` SET `support`='"+item["support"]+"', `unsupport`='"+item["unsupport"]+"', `time`='"+item["time"]+"' WHERE `id`='"+item["_id"]+"'"
			lines = self.cursor.execute(sql)
			self.db.commit()
			raise DropItem("Comment %s is exist. Update support, unsupport and time information" % (item["_id"],))